package pl.edu.uw.come.mooba.util;

import pl.edu.uw.come.mooba.domain.exceptions.InvalidMoodleBackupArchiveException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 *
 * @author Piotr Kochański
 */
public class ZipArchiveTools {

    private static final String MOODLE_1X_BACKUP_FILE_NAME = "moodle.xml";

    /**
     * Extracts from Moodle archive file XML file with backup description.
     * @param toDir
     * @param zf
     */
    public static File extractMoodle1XBackupFile(ZipFile zf, File toDir) throws IOException, InvalidMoodleBackupArchiveException{
        if (!toDir.isDirectory()) {
            if (!toDir.mkdirs())
                throw new IOException("Failed to create " + toDir);
        }

        byte[] buf = new byte[4096];
        int n;

        ZipEntry backupDescFileZE = zf.getEntry(MOODLE_1X_BACKUP_FILE_NAME);
        if(backupDescFileZE == null){
            throw new InvalidMoodleBackupArchiveException("No " + MOODLE_1X_BACKUP_FILE_NAME + " file present in backup archive");
        }
        File backupDescFile = new File(toDir, backupDescFileZE.getName());

        InputStream ins = zf.getInputStream(backupDescFileZE);
        OutputStream outs = new FileOutputStream(backupDescFile);
        while ((n = ins.read(buf)) != -1)
            outs.write(buf, 0, n);
        ins.close();
        outs.close();
        return backupDescFile;
    }
}
